package com.qidian.mes.cal.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qidian.mes.cal.mapper.DepartmentMapper;
import com.qidian.mes.cal.service.DepartmentService;
import com.qidian.mes.pojo.Department;
import com.qidian.mes.util.pojo.MESResult;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class DepartmentServiceImpl implements DepartmentService {
    @Autowired
    DepartmentMapper departmentMapper;

    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    @Override
    //查询所有部门
    public MESResult list(int page, int limit) {
        // 先查询1级别类目  这里调用了一个递归查询的方法
        // 获取DepartmentService的代理对象
        DepartmentService departmentService = (DepartmentService) AopContext.currentProxy();
        List<Department> departments = departmentService.selectByParentId(0L);
        // 开启分页 在当前线程中执行下一条SQL的时候就会进行分页。
        PageHelper.startPage(page, limit);
        // 组织一个分页对象。（页码，每页大小，最大页码，数据，总条数）
        PageInfo<Department> pageInfo = new PageInfo<>(departments);
        return MESResult.ok(departments);
    }

    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    @Override
    //子权限集合
    public List<Department> selectByParentId(Long parentId) {
        DepartmentService departmentService = (DepartmentService) AopContext.currentProxy();
        List<Department> departments = departmentMapper.list(parentId);
        for (Department department : departments) {
            if(department.getParent().equals(2)){
                // 有子权限，递归查询
                department.setChildren(departmentService.selectByParentId(department.getDepartmentId()));
            }
        }
        return departments;
    }


}
